from django.conf import settings
import hashlib

class OrderQueryPay(object):
    def __init__(self, order_id, nonce_str):
        """
        :param order_id: 订单编号，32字符以内
        :param nonce_str: 32位随机字符串
        """
        self.api_key = settings.WECHAT_PAY_API_KEY
        self.params = {
            'appid': settings.WECHAT_APP_ID,
            'mch_id': settings.WECHAT_PAY_ID,
            'nonce_str': nonce_str,
            'out_trade_no': order_id,
        }

        self.WxOrderQueryPay_request_url = 'https://api.mch.weixin.qq.com/pay/orderquery'  # 小程序发起支付链接
        self.error = None

    def key_value_url(self, value):
        # 将键值对转换成key1=value1&key2=value2
        string_sign = ''
        for k in sorted(value.keys()):  # sorted : ASCII字典序排序
            string_sign += "{0}={1}&".format(k, value[k])
        print('键值对：', string_sign)
        return string_sign

    def get_sign(self, params):
        """
        生成sign签名
        :param params: 传入参数
        :return:
        """
        stringA = self.key_value_url(params)
        stringSignTemp = stringA + 'key=' + self.api_key  # APIKEY,API密钥，需要在商户后台设置
        print('最终键值对:', stringSignTemp)
        sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
        print("最终生成的签名：", sign)
        params['sign'] = sign

    def get_req_xml(self):
        """
        拼接xml
        :return:
        """
        self.get_sign(self.params)
        xml = "<xml>"
        for k in sorted(self.params.keys()):
            xml += '<{0}>{1}</{0}>'.format(k, self.params[k])
        xml += "</xml>"
        print("得到的XML：", xml)
        return xml.encode('utf-8')

    def get_pay_result(self):
        """
        请求获取支付结果
        :return:
        """
        import requests
        from xml.etree import ElementTree as et
        xml = self.get_req_xml()
        unifiedorderXML = requests.post(self.WxOrderQueryPay_request_url, data=xml)
        unifiedorderXML.encoding = 'utf-8'
        unifiedorderXML = unifiedorderXML.text
        print("统一下单接口返回的接口数据", unifiedorderXML)
        root = et.fromstring(unifiedorderXML)
        if root.find("result_code").text != 'SUCCESS':
            self.error = root.find("err_code_des").text
            print(self.error)
        pay_result = root.find("trade_state").text
        if  pay_result == 'SUCCESS':
            self.params['transaction_id'] = root.find('transaction_id').text  # 微信订单号
            self.params['total_fee'] = root.find('total_fee').text  # 付款总金额，使用完商户内部优惠券后的金额
            self.params['pay_result'] = pay_result
        else:
            self.params['pay_result'] = pay_result
            self.params['transaction_id'] = ''  # 微信订单号
            self.params['total_fee'] = ''  # 付款总金额，使用完商户内部优惠券后的金额
        # 移除其他不需要返回参数
        print('最后一步：', self.params)
        parms_keys = []
        for i in self.params.keys():
            parms_keys.append(i)
        for i in parms_keys:
            if i not in ['pay_result','transaction_id','total_fee',]:
                self.params.pop(i)
        print('返回给后台的parms', self.params)
        return self.params
